import React, { lazy, Suspense } from "react";
import { Navigate } from "react-router-dom";

// import XJHDiscover from "@/pages/discover";
// import XJHFriend from "@/pages/friend";
// import XJHMine from "@/pages/mine";
import Lazyload from "@/pages/lazyload";

const XJHDiscover = () => import("@/pages/discover");
const XJHFriend = () => import("@/pages/friend");
const XJHMine = () => import("@/pages/mine");

// import XJHRecommend from "@/pages/discover/c-pages/recommend";
const XJHRecommend = () => import("@/pages/discover/c-pages/recommend");
const XJHAlbum = () => import("@/pages/discover/c-pages/album");
const XJHArtist = () => import("@/pages/discover/c-pages/artist");
const XJHDjradio = () => import("@/pages/discover/c-pages/djradio");
const XJHRanking = () => import("@/pages/discover/c-pages/ranking");
const XJHSongs = () => import("@/pages/discover/c-pages/songs");
const XJHPlayer = () => import("@/pages/player");

const routes = [
  {
    path: "/",
    exact: true,
    jump: true,
    element: <Navigate to="discover" />,
  },
  {
    path: "discover/*",
    exact: true,
    element: XJHDiscover,
    children: [
      {
        path: "",
        exact: true,
        jump: true,
        element: <Navigate to="recommend" />,
      },
      {
        path: "recommend",
        exact: true,
        element: XJHRecommend,
      },
      {
        path: "album",
        exact: true,
        element: XJHAlbum,
      },
      {
        path: "artist",
        exact: true,
        element: XJHArtist,
      },
      {
        path: "djradio",
        exact: true,
        element: XJHDjradio,
      },
      {
        path: "ranking",
        exact: true,
        element: XJHRanking,
      },
      {
        path: "songs",
        exact: true,
        element: XJHSongs,
      },
      {
        path: "player",
        exact: true,
        element: XJHPlayer,
      },
    ],
  },
  {
    path: "/friend",
    exact: true,
    element: XJHFriend,
  },
  {
    path: "/mine",
    exact: true,
    element: XJHMine,
  },
];

function LazyElement(props) {
  const { importFunc } = props;
  const LazyComponent = lazy(importFunc);
  return (
    <Suspense fallback={<Lazyload />}>
      <LazyComponent />
    </Suspense>
  );
}

// 处理routes 如果element是懒加载，要包裹Suspense
function dealRoutes(routesArr) {
  if (routesArr && Array.isArray(routesArr) && routesArr.length > 0) {
    routesArr.forEach((route) => {
      if (!route.jump && route.element && typeof route.element == "function") {
        const importFunc = route.element;
        route.element = <LazyElement importFunc={importFunc} />;
      }
      if (route.children) {
        dealRoutes(route.children);
      }
    });
  }
}

dealRoutes(routes);

export default routes;
